# -*- coding: utf-8 -*-
import json

from utils.file_utils import FileUtils


class JsonUtils:

    @staticmethod
    def json_path_str(path):
        """
        读取文件
        :param path:
        :return:
        """
        if FileUtils.file_exists(path):
            data = FileUtils.read_file(path)
            return data
        else:
            raise Exception(f"文件不存在")

    @staticmethod
    def json_to_obj(data, has_true=False):
        """
        转换json字符串到对象
        :param data:
        :param has_true:
        :return:
        """
        if has_true:
            data = data.replace('True', 'true')
            data = data.replace('False', 'false')
            data = data.replace('\'', '"')
        return json.loads(data)

    @staticmethod
    def format_str(data):
        return eval(data)

    @staticmethod
    def format_json_str(data, indent=4, sort=False):
        """
        将字符串或者对象格式化成带格式的json字符串
        :param data:
        :param indent:
        :param sort:
        :return:
        """
        if type(data) == str:
            data = eval(data)
        return json.dumps(data, indent=indent, sort_keys=sort, ensure_ascii=False)

    @staticmethod
    def format_json(data):
        """
        格式化带True的文本
        :param data:
        :return:
        """
        return JsonUtils.format_json_str(JsonUtils.json_to_obj(data, True))

    @staticmethod
    def write_json(data, path, has_true=False, indent=4):
        """
        将json字符串写入到文本
        :param path:
        :param has_true:
        :param indent:
        :return:
        """
        with open(path, 'w', encoding="utf-8") as f:
            json.dump(json.loads(json.dumps(eval(data))), f, indent=4)

    @staticmethod
    def write_str_json(data, path, has_true=False):
        """
        将字符串写入到文件
        :param path:
        :param has_true:
        :return:
        """
        if has_true:
            data = data.replace("true", "True")
            data = data.replace("false", "False")
        with open(path, "w", encoding="utf-8") as file:
            file.writelines(data)

    @staticmethod
    def is_json(data):
        """
        判断是否是json字符串
        """
        try:
            json.JSONDecoder().raw_decode(data)
            return True
        except json.JSONDecodeError:
            return False

if __name__ == '__main__':
    print("Python")
